package com.ruoyi.common.cron;

import cn.hutool.cron.CronUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ruoyi.common.exception.UtilException;
import com.ruoyi.common.utils.CronUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * SysJobListener
 * 定时任务监听器，系统启动时将定时任务启动
 *
 * @author kylewka
 * @since 2025/1/6
 */
@Slf4j
@Configuration
@SuppressWarnings("all")
public class CronJobListener implements ApplicationListener<ApplicationStartedEvent>, Ordered {

    @Override
    public int getOrder() {
        return LOWEST_PRECEDENCE;
    }

    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        // 获取所有CronJobInterface实现类
        String[] cronBeans = SpringUtils.getBeanNamesForType(CronJobInterface.class);
        if (cronBeans.length == 0) {
            log.warn("定时任务加载接口未实现: {}", CronJobInterface.class.getName());
        } else if (cronBeans.length > 1) {
            throw new UtilException("定时任务加载接口存在多个实现");
        } else {
            // 获取实现类并加载定时任务
            CronJobInterface cronJobInterface = SpringUtil.getBean(CronJobInterface.class);
            cronJobInterface.loadCronJobs().forEach(CronUtils::addJob);
            CronUtil.setMatchSecond(true);
            CronUtil.restart();
        }
    }


}
